package com.book.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class DBUtil {

	static String user = ""; //用户名
	static String password = ""; //数据库登录密码
	static String url = ""; //数据库连接url
	static String driver = ""; //驱动类名称

	static {

		InputStream inputStream = DBUtil.class.getClassLoader()
				.getResourceAsStream("db.properties");
		Properties properties = new Properties();
		try {
			properties.load(inputStream);
			user = properties.getProperty("user");
			password = properties.getProperty("password");
			url = properties.getProperty("url");
			driver = properties.getProperty("driver");
			
			Class.forName(driver);
		} catch (IOException e) {

			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

	}
   /**
    * 获取连接
    * @return
    */
	public static Connection getConnection() {
		Connection connection = null;
		try {
			connection = DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return connection;

	}
	/**
	 * 关闭连接资源。
	 * @param preparedStatement 预处理 
	 * @param resultSet  结果集
	 * @param connection  连接
	 */
	public static void closeConnection(PreparedStatement preparedStatement,ResultSet resultSet,Connection connection){
		if(resultSet!=null){
			try {
				resultSet.close();
			} catch (SQLException e) {
				
				e.printStackTrace();
			}finally{
				if (preparedStatement!=null) {
					try {
						preparedStatement.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}finally{
						if (connection!=null) {
							try {
								connection.close();
							} catch (SQLException e) {
								e.printStackTrace();
							}
						}
					}
				}
			}
		}
		
	}

}
